package com.yr.ryjk.user.service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSONObject;
import com.yr.ryjk.coin.dao.CoinRecordMapper;
import com.yr.ryjk.coin.entity.CoinRecord;
import com.yr.ryjk.common.Constant;
import com.yr.ryjk.common.ErrorType;
import com.yr.ryjk.common.Pagination;
import com.yr.ryjk.doctor.dao.DoctorMapper;
import com.yr.ryjk.doctor.entity.Doctor;
import com.yr.ryjk.jpush.JPushType;
import com.yr.ryjk.jpush.JpushMessage;
import com.yr.ryjk.jpush.JpushSendService;
import com.yr.ryjk.param.dao.ParamMapper;
import com.yr.ryjk.param.entity.Key;
import com.yr.ryjk.redis.JedisUtil;
import com.yr.ryjk.user.dao.UserMapper;
import com.yr.ryjk.user.entity.User;
import com.yr.ryjk.user.entity.UserRegisterModel;
import com.yr.ryjk.user.vo.UserVO;
import com.yr.ryjk.util.IDGenerator;
import com.yr.ryjk.util.JSONUtil;

@Service
public class UserService implements IUserService{
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private DoctorMapper doctorMapper;
	@Autowired
	private ParamMapper paramMapper;
	@Autowired
	private CoinRecordMapper coinRecordMapper;
	
	@Override
	public User getUserById(String id) {
		User user=userMapper.selectByPrimaryKey(id);
		if(user!=null){
			user.setPassword(null);   //屏蔽掉关键信息
			user.setCoinMd5(null);
		}
		return user;
	}

	@Override
	public Map<String, Object> getListOfPage(int pageNo, int pageSize,String name,String phone) {
		List<User> list=userMapper.selectOfPage((pageNo-1)*pageSize,pageSize,name,phone);
		int count=userMapper.selectCount(name,phone);
		
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("list", list);
		map.put("pagination", new Pagination(pageSize,pageNo,count));
		
		return map;
	}

	@Override
	public Map<String, Object> addRegister(UserRegisterModel user) throws IllegalAccessException, InvocationTargetException {
		//1.判断phone的唯一性
		int count=userMapper.selectCountByPhone(user.getPhone());
		if(count>0){
			return JSONUtil.getJSON(ErrorType.PHONE_HAS_REGISTERED_ERROR);
		}
		Doctor doctor=doctorMapper.selectByPhone(user.getPhone());
		if(doctor!=null){
			return JSONUtil.getJSON(ErrorType.PHONE_HAS_REGISTERED_ERROR);
		}
		
		int coin = Integer.parseInt(paramMapper.selectCountByKey(Key.coins_default_count.getKey())); //账户默认注册得到的健康币
		//2.设置属性
		User dest=new User();
		BeanUtils.copyProperties(dest, user);
		dest.setId(IDGenerator.gen32UUID());
		dest.setRegisterTime(new Date());
		dest.setCoin(coin);
		dest.setCoinMd5(DigestUtils.md5DigestAsHex((coin+Constant.COIN_MD5_SECRET_KEY).getBytes()));
		dest.setPassword(DigestUtils.md5DigestAsHex(dest.getPassword().getBytes()));
		
		//3.健康币收支记录
		if(coin>0){
			CoinRecord cr=new CoinRecord();
			cr.setCoinRecordId(IDGenerator.gen32UUID());
			cr.setType(6);
			cr.setCount(coin);
			cr.setUserId(dest.getId());
			cr.setOperateTime(new Date());
			cr.setContent("注册送"+coin+"个健康币");
			coinRecordMapper.insert(cr);
		}
		//4.保存
		userMapper.insert(dest);
		return JSONUtil.getJSON(ErrorType.SUCCESS,coin);
	}
	
	@Override
	public Map<String, Object> updatelogin(String phone, String password,String jpushKey) 
			throws IllegalAccessException, InvocationTargetException {
		//1.验证信息
		User user=userMapper.selectUserByPhone(phone);
		if(user!=null){
			if(DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())){
				String token=IDGenerator.gen32UUID();
				userMapper.updateLoginTime(phone,new Date());

				//2.登录互斥，不允许多部设备同时登录一个帐号
				final String jpushKeyInRedis=JedisUtil.getJPushKeyByPhone(phone);
				if(jpushKeyInRedis!=null&&!jpushKeyInRedis.equals(jpushKey)){          //使同一帐号的其他设备下线
					new Thread(new Runnable() {                  //新开线程，避免阻塞
						@Override
						public void run() {
							try {
								final JpushMessage msg = new JpushMessage();
								msg.setName("user");             //特殊用途，用于告诉app登录用户的身份
								msg.setType(JPushType.need_login);
								
								String jpushMap =  JSONObject.toJSON(msg).toString();
								JpushSendService.sendAndroidMessage(jpushMap, new String[]{jpushKeyInRedis});
							} catch (Exception e) {
								e.printStackTrace();
								//消息推送异常,是可以允许的异常
							}
						}
					}).start();
				}
				
				//3.覆盖登录信息
				JedisUtil.putPhoneTokenMap(phone, token);
				JedisUtil.putTokenPhoneMap(token, phone);
				JedisUtil.putPhoneJPushMap(phone, jpushKey);
				JedisUtil.putJPushPhoneMap(jpushKey,phone);

				//4.将信息返回给app
				UserVO uvo=new UserVO();
				BeanUtils.copyProperties(uvo, user);
				uvo.setToken(token);
				return JSONUtil.getJSON(ErrorType.SUCCESS,uvo);
			}
		}
		return JSONUtil.getJSON(ErrorType.LOGIN_ERROR);
	}

	@Override
	public Map<String, Object> modifyResetPassword(String phone, String newPassword) {
		int manageCount=userMapper.updatePasswordByPhone(phone,DigestUtils.md5DigestAsHex(newPassword.getBytes()));
		if(manageCount>0){
			return JSONUtil.getJSON(ErrorType.SUCCESS);
		}
		return JSONUtil.getJSON(ErrorType.TOKEN_ERROR);
	}

	@Override
	public Map<String, Object> modifyPassword(String oldPassword,
			String newPassword, String token) {
		String phone=JedisUtil.getPhoneByToken(token);
		if(phone!=null){
			User user=userMapper.selectUserByPhone(phone);
			if(user!=null){
				if(user.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))){
					userMapper.updatePasswordByPhone(phone,DigestUtils.md5DigestAsHex(newPassword.getBytes()));
					return JSONUtil.getJSON(ErrorType.SUCCESS);
				}else {
					return JSONUtil.getJSON(ErrorType.PASSWORD_ERROR);
				}
			}
		}
		return JSONUtil.getJSON(ErrorType.TOKEN_ERROR);
	}

	@Override
	public void deleteById(String id) {
//		userMapper.deleteByPrimaryKey(id);
	}
	public Map<String, Object> getMesById(String id){
		return JSONUtil.getJSON(ErrorType.SUCCESS, userMapper.getCensusById(id));
	}
}